package com.hanxiaozhang.config;


import com.hanxiaozhang.constant.RabbitConstant;
import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.core.RabbitAdmin;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

/**
 * 〈一句话功能简述〉<br>
 * 〈〉
 *
 * @author hanxinghua
 * @create 2022/9/21
 * @since 1.0.0
 */
@Configuration
public class HeadersRabbitConfig implements BeanPostProcessor {
   
    @Resource
    private RabbitAdmin rabbitAdmin;

    /**
     * 创建队列A
     *
     * @return
     */
    @Bean
    public Queue headersQueueA() {
        return new Queue(RabbitConstant.HEADERS_QUEUE_A, true, false, false);
    }

    /**
     * 创建队列B
     *
     * @return
     */
    @Bean
    public Queue headersQueueB() {
        return new Queue(RabbitConstant.HEADERS_QUEUE_B, true, false, false);
    }

    /**
     * 配置HeadersExchange交换机
     *
     * @return
     */
    @Bean
    public HeadersExchange rabbitHeadersExchange() {
        return new HeadersExchange(RabbitConstant.HEADERS_EXCHANGE, true, false);
    }

    /**
     * 队列A绑定到HeadersExchange交换机
     *
     * @return
     */
    @Bean
    public Binding bindHeadersA() {
        Map<String, Object> map = new HashMap<>(4);
        map.put("key_one", "java");
        map.put("key_two", "c");
        // 全匹配
        return BindingBuilder.bind(headersQueueA())
                .to(rabbitHeadersExchange())
                .whereAll(map).match();
    }

    /**
     * 队列B绑定到HeadersExchange交换机
     *
     * @return
     */
    @Bean
    public Binding bindHeadersB() {
        Map<String, Object> map = new HashMap<>(4);
        map.put("headers_A", "a");
        map.put("headers_B", "b");
        // 部分匹配
        return BindingBuilder.bind(headersQueueB())
                .to(rabbitHeadersExchange())
                .whereAny(map).match();
    }

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        rabbitAdmin.declareExchange(rabbitHeadersExchange());
        rabbitAdmin.declareQueue(headersQueueA());
        rabbitAdmin.declareQueue(headersQueueB());
        return null;
    }

}
